package com.yimi.yinhepda.views.stockCheck_module;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import butterknife.Bind;

import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.CheckBillAdapter;
import com.yimi.yinhepda.adapter.SpinnerAdapter;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.CheckScanTableDao;
import com.yimi.yinhepda.db.table.CheckScanTable;
import com.yimi.yinhepda.entity.bean.CheckEntity;
import com.yimi.yinhepda.entity.request.CheckUpdateRetentionRequest;
import com.yimi.yinhepda.entity.response.CheckScanTaskResponse;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.Constants;
import com.yimi.yinhepda.utils.IntentUtils;
import com.yimi.yinhepda.base.BaseInitActivity;
import com.yimi.yinhepda.views.exceptionsUpload_module.ProblemBillUploadActivity;

import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 盘点扫描详细界面.
 *
 * @author 000432
 */
public class CheckWaybillDetailActivity extends BaseInitActivity implements View.OnTouchListener, AdapterView.OnItemClickListener {
    /**
     * 标题栏左边.
     */
    @Bind(R.id.title)
    TextView mTvTitle;
    /**
     * 标题栏中间.
     */
    @Bind(R.id.num)
    TextView mTvNum;
    @Bind(R.id.activity_compare_waybill)
    EditText mEditWayBill;
    @Bind(R.id.activity_compare_listview)
    ListView mListView;
    @Bind(R.id.activity_compare_back)
    Button mBtnBack;
    /**
     * 总件数.
     */
    @Bind(R.id.load_compare_zj)
    TextView mTvTotal;
    /**
     * 已扫描件数.
     */
    @Bind(R.id.load_compare_scaned)
    TextView mTvScannedNum;
    /**
     * 未扫描件数.
     */
    @Bind(R.id.load_compare_not_scaned)
    TextView mTvNotScannedNum;
    /**
     * 实重.
     */
    @Bind(R.id.activity_compare_realWeightQty)
    TextView mTvRealWeight;
    /**
     * 计重.
     */
    @Bind(R.id.activity_compare_meterageWeightQty)
    TextView mTvComputeWeight;
    /**
     * 体积.
     */
    @Bind(R.id.activity_compare_volume)
    TextView mTvVolume;
    @Bind(R.id.dwbda_scrollView)
    ScrollView mv_scrollView;
    /**
     * 运单号.
     */
    private String mCheckWayBillNo;
    private CheckBillAdapter mAdapter;
    /**
     * 显示子单列表集合
     */
    private List<CheckEntity> mCheckList = new ArrayList<>();
    /**
     * 盘点数据列表
     */
    private List<CheckScanTaskResponse.CheckScanEntity> mCheckScanList;
    /**
     * 盘点号
     */
    private String mStockNo;
    /**
     * 滞留原因list
     */
    private List<String> mRetentionList;
    /**
     * 首次是否为空
     */
    private boolean isSpFirstNull;
    private String spinnerRetentionData;

    @Override
    public String getPageName() {
        return getString(R.string.page_check_billdetail);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_check_waybill_detail;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        //标题
        mTvTitle.setText(getString(R.string.check_waybillno_title));

        mCheckScanList = CheckScanActivity.mCheckScanList;
        //运单号
        mCheckWayBillNo = getIntent().getStringExtra(IntentUtils.BUILD_WAYBILLNO);
        mEditWayBill.setText(mCheckWayBillNo);
        mStockNo = getIntent().getStringExtra("stockNo");
        //滞留原因
        mRetentionList = (List<String>) getIntent().getSerializableExtra("retentionList");
    }

    @Override
    public void initEvent() {
        mBtnBack.setOnClickListener(this);
        findViewById(R.id.activity_compare_changeProblem).setOnClickListener(this);
        mListView.setOnTouchListener(this);
        mListView.setOnItemClickListener(this);
        mv_scrollView.setOnTouchListener(this);
    }

    @Override
    public void initData() {
        if (mCheckScanList == null || mCheckScanList.size() <= 0) {
            return;
        }
        for (int i = 0; i < mCheckScanList.size(); i++) {
            //运单对象
            CheckScanTaskResponse.CheckScanEntity currentItemInfo = mCheckScanList.get(i);

            if (currentItemInfo.getWaybillNo().equals(mCheckWayBillNo)) {
                //子单集合
                List<CheckScanTaskResponse.ChildInfo> childList = currentItemInfo.getStocktakingDiffreportInventoryList();
                if (childList == null) {
                    return;
                }
                //循环出单个子单
                for (CheckScanTaskResponse.ChildInfo childInfo : childList) {
                    CheckEntity checkEntity = new CheckEntity();
                    checkEntity.setChildWayBillNo(childInfo.getWaybillChildNo());
                    if (childInfo.getColumn1() != null && !childInfo.getColumn1().equals("")) {
                        try {
                            int retention = Integer.parseInt(childInfo.getColumn1());
                            checkEntity.setRetention(mRetentionList.get(retention - 1));
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                    }
                    /** 扫描的单子发现在任务中*/
                    if (childInfo.getStockStatus() == 0) {
                        checkEntity.setStatus(0);
                    } else {
                        checkEntity.setStatus(1);
                    }

                    //列表显示
                    mCheckList.add(checkEntity);

                    //总件数，已扫描，未扫描
                    mTvTotal.setText(childList.size() + "");
                    mTvScannedNum.setText(currentItemInfo.getScannedNum() + "");
                    mTvNotScannedNum.setText(childList.size() - currentItemInfo.getScannedNum() + "");

                    //实重，计重，体积
                    mTvRealWeight.setText(currentItemInfo.getRealWeight() + "kg");
                    mTvComputeWeight.setText(currentItemInfo.getChargeableWeight() + "kg");
                    mTvVolume.setText(currentItemInfo.getVolume() + "m³");
                }
                break;
            }
        }
        //comparator接口进行字符串的大小排序
        Collections.sort(mCheckList, new Comparator<CheckEntity>() {
            @Override
            public int compare(CheckEntity t0, CheckEntity t1) {
                return t0.getChildWayBillNo().compareTo(t1.getChildWayBillNo());
            }
        });
        //comparable接口进行是否扫描的状态排序
        Collections.sort(mCheckList);
        mAdapter = new CheckBillAdapter(this, mCheckList, mRetentionList);
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.activity_compare_back) {
            finish();
        } else if (v.getId() == R.id.activity_compare_changeProblem) {
            Intent intent = new Intent(this, ProblemBillUploadActivity.class);
            intent.putExtra(IntentUtils.WAYBILLNO, mEditWayBill.getText().toString());
            startActivity(intent);
            finish();
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()) {
            case R.id.activity_compare_listview:
                mListView.requestDisallowInterceptTouchEvent(true);
                break;
            default:
                mv_scrollView.requestDisallowInterceptTouchEvent(true);
                break;
        }
        return false;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //显示选择滞留原因对话框
        showSelectRetentionDialog(position);
    }

    /**
     * 显示选择滞留原因对话框.
     */
    private void showSelectRetentionDialog(int position) {
        final CheckEntity entity = mCheckList.get(position);
        final LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.alert_dialog_retention_select, null);
        //子单号
        TextView tvChildWayBill = layout.findViewById(R.id.tv_childWayBill);
        tvChildWayBill.setText(entity.getChildWayBillNo());
        //滞留原因
        final Spinner spRetention = (Spinner) layout.findViewById(R.id.sp_retention);

        if (mRetentionList == null || mRetentionList.size() <= 0) {
            spRetention.setPrompt("请先维护滞留原因");
        } else {
            spRetention.setPrompt("请选择滞留原因");
        }
        if (entity.getRetention() == null || entity.getRetention().equals("")) {
            isSpFirstNull = true;
        } else {
            isSpFirstNull = false;
        }

        SpinnerAdapter mRetentionAdapter = new SpinnerAdapter(this, R.layout.simple_spinner_item, mRetentionList);
        spRetention.setAdapter(mRetentionAdapter);
        boolean hasRetention = false;
        for (int i = 0; i < mRetentionList.size(); i++) {
            if (entity.getRetention() != null && entity.getRetention().equals(mRetentionList.get(i))) {
                hasRetention = true;
                spinnerRetentionData = (i + 1) + "";
                spRetention.setSelection(i, true);
            }
        }
        if (!hasRetention) {
            try {
                spRetention.setSelection(Integer.parseInt(entity.getRetention()) - 1, true);
                spinnerRetentionData = entity.getRetention();
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        spRetention.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isSpFirstNull) {
                    spinnerRetentionData = "";
                    //第一次不显示默认的第一项
                    view.setVisibility(View.INVISIBLE);
                    isSpFirstNull = false;
                } else {
                    spinnerRetentionData = (position + 1) + "";
                    view.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        spRetention.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //解决spinner的item点击事件只能点击一次
                try {
                    Class<?> clazz = AdapterView.class;
                    Field field = clazz.getDeclaredField("mOldSelectedPosition");
                    field.setAccessible(true);
                    field.setInt(spRetention, AdapterView.INVALID_POSITION);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }
        });

        //返回按钮
        Button btnBack =  layout.findViewById(R.id.btn_back);
        //确定按钮
        Button btnOK =  layout.findViewById(R.id.btn_sure);
        final Dialog dialog = new Dialog(this, R.style.AsyncTaskDialog);
        dialog.addContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.getWindow().getDecorView().setPadding(10, 0, 10, 0);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        btnOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //调用接口修改该件的滞留信息
                requestUpdateRetention(dialog, entity);
            }
        });
    }

    /**
     * 请求接口修改滞留原因
     */
    private void requestUpdateRetention(final Dialog dialog, final CheckEntity entity) {
        showPgDlg("数据修改中...");
        CheckUpdateRetentionRequest request = new CheckUpdateRetentionRequest();
        //盘点单号
        request.setStockNo(mStockNo);
        //运单号
        request.setWaybillNo(Long.parseLong(mCheckWayBillNo));
        //子单号
        request.setWaybillChildNo(entity.getChildWayBillNo());
        //备注（滞留原因）
        request.setNote(spinnerRetentionData);
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(CheckScanTaskResponse.class)
                .setUrl(Constants.URL_UPDATE_STOCK_TAKING_DETAILS)
                .setRequestObject(request)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        dialog.dismiss();
                        entity.setRetention(spinnerRetentionData);
                        mAdapter.notifyDataSetChanged();
                        //修改缓存数据的滞留信息
                        for (int i = 0; i < mCheckScanList.size(); i++) {
                            //运单对象
                            CheckScanTaskResponse.CheckScanEntity currentItemInfo = mCheckScanList.get(i);
                            if (currentItemInfo.getWaybillNo().equals(mCheckWayBillNo)) {
                                //子单集合
                                List<CheckScanTaskResponse.ChildInfo> childList = currentItemInfo.getStocktakingDiffreportInventoryList();
                                if (childList == null) {
                                    return;
                                }
                                //循环出单个子单
                                for (CheckScanTaskResponse.ChildInfo childInfo : childList) {
                                    if (entity.getChildWayBillNo().equals(childInfo.getWaybillChildNo())) {
                                        childInfo.setColumn1(entity.getRetention());
                                        break;
                                    }
                                }
                            }
                        }
                        //修改数据库中扫描的滞留信息
                        CheckScanTableDao mCheckScanTableDao = new CheckScanTableDao();
                        CheckScanTable checkScanTable = mCheckScanTableDao.getChildWaybillNoData(mStockNo, entity.getChildWayBillNo());
                        if (checkScanTable != null) {
                            checkScanTable.setRetention(entity.getRetention());
                            try {
                                mCheckScanTableDao.update(checkScanTable);
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }
}
